package com.shop.inteceptorApp;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.shop.dto.UserInfo;
import com.shop.local.UserInfoLocal;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wzby
 * @Date: 2022/10/16 10:50
 */

public class AuthorityInterceptor implements HandlerInterceptor {

    private String TOKEN_SECRET;

    public AuthorityInterceptor(String token_secret) {
        this.TOKEN_SECRET = token_secret;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("Authorization");

        //校验是否为空
        if (StrUtil.isEmpty(token)){
//            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,"信息错误");
            response.setContentType("authorization/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"message\":\"token不能为空\"}");
            return false;
        }

        //校验是否正确（合法）
        boolean isTrue = false;
        try {
         isTrue = JWTUtil.verify(token,TOKEN_SECRET.getBytes());
        }catch (Exception exception){
            exception.printStackTrace();
        }
        if (isTrue == false){
            response.setContentType("authorization/json;charset=utf-8");
            response.getWriter().write("{\"code\":401,\"message\":\"token错误或已过期\"}");
            return false;
        }
        //走到这个位置，说明token是正确合法的
        final JWT jwt = JWTUtil.parseToken(token);
        UserInfo userInfo = JSONUtil.toBean(jwt.getPayload().toString(), UserInfo.class);
        UserInfoLocal.set(userInfo);

        //当前线程名称
        System.out.println("52:->"+Thread.currentThread().getName());
        return true;
    }
}
